package com.example.autopia.view.Activities

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.autopia.databinding.ActivityMyNewsBinding
import com.example.autopia.model.Item.News
import com.example.autopia.model.Repositories.NewsRepository
import com.example.autopia.model.Repositories.UsersRepository
import com.example.autopia.view.Adapters.NewsAdapter
import com.example.autopia.view.Listeners.ActionNewsListener
import com.example.autopia.view.Listeners.PostNewsListener
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase

class MyNewsActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMyNewsBinding
    private val newsRepository = NewsRepository()
    private val userRepository = UsersRepository()
    private val adapter = NewsAdapter()
    private val firebaseAuth = Firebase.auth
    private var userid: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMyNewsBinding.inflate(layoutInflater)
        setContentView(binding.root)
        userid = intent.getStringExtra("id")//Получаем id пользователя
        binding.btBack.setOnClickListener {
            finish()
        }

        binding.recyclerView.adapter = adapter
        if (!userid.isNullOrEmpty()) {//Наш или не наш список
            getData(userid!!)
        } else {
            getData(firebaseAuth.currentUser?.uid ?: "")
        }

        adapter.attachListenerPost(object : PostNewsListener {
            override fun onAddCommentClick(news: News) {//Добавление коментария
                val intent = Intent(this@MyNewsActivity,CommentsActivity::class.java)
                intent.putExtra("newsId",news.id)
                startActivity(intent)
            }
            override fun onAddLikeClick(news: News, isAdd: Boolean) {//Добавление/убавление лайка
                if (isAdd) {
                    newsRepository.addLike(newsId = news.id)
                    userRepository.addLikesNews(firebaseAuth.currentUser?.uid ?: "", news.id)
                } else {
                    newsRepository.removeLike(newsId = news.id)
                    userRepository.removeLikesNews(firebaseAuth.currentUser?.uid ?: "", news.id)
                }
            }
            override fun onMoreClick(news: News) {//Поделиться
                val intent = Intent(Intent.ACTION_SEND)
                intent.type = "text/plain"
                intent.putExtra(
                    Intent.EXTRA_TEXT,
                    "Обсуждение из 'Autopia'" + "\n \n" + news.title + "\n \n" + news.mainText + "\n \n" + news.name
                )
                startActivity(Intent.createChooser(intent, "Поделиться с помощью"))
            }
            override fun onDeleteClick(news: News) {//Удалить
                newsRepository.deleteNews(newsId = news.id)
                Toast.makeText(this@MyNewsActivity,"Обсуждение удалено", Toast.LENGTH_SHORT).show()
                if (!userid.isNullOrEmpty()) {
                    getData(userid!!)
                } else {
                    getData(firebaseAuth.currentUser?.uid ?: "")
                }
            }
            override fun onChannelCLick(userid: String) {}//Не переходим так как и так своё
        })
        adapter.attachListenerAction(object : ActionNewsListener {
            override fun onAddNewsClick() {}
            override fun onMyNewsClick() {}
            override fun onNewsChannelsClick() {}
        })
    }

    private fun getData(userid: String) {//Получение данных
        var list = ArrayList<News>()
        val items = newsRepository.getAllItems()
        items.observe(this) {
            val sortList = it.sortedByDescending  { news -> news.time}
            list.addAll(sortList)
            val user = userRepository.getUserById(userid)
            user.observe(this) { curUser ->
                if (curUser.id != (firebaseAuth.currentUser?.uid ?: "")) {//Если наши обсуждения то наши, если другого то другого
                    binding.title.text = curUser.name
                } else {
                    binding.title.text = "Мои обсуждения"
                }
                list = list.filter { news -> news.userid.contains(curUser.id) } as ArrayList<News>
                list.add(list.size,News("1","","1",1,null,"1","1",4,""))
                adapter.setData(list, curUser.likesNewsList!!)
                binding.loading.visibility = View.GONE
            }
        }
    }
}